<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>文本情感分析系统</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css" rel="stylesheet">
    <script>
        tailwind.config = {
            theme: {
                extend: {
                    colors: {
                        primary: '#3B82F6',
                        secondary: '#10B981',
                        neutral: '#6B7280',
                        positive: '#10B981',
                        negative: '#EF4444',
                        neutral: '#6B7280',
                    },
                    fontFamily: {
                        sans: ['Inter', 'system-ui', 'sans-serif'],
                    },
                }
            }
        }
    </script>
    <style type="text/tailwindcss">
        @layer utilities {
            .content-auto {
                content-visibility: auto;
            }
            .card-shadow {
                box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
            }
            .animate-fade-in {
                animation: fadeIn 0.5s ease-in-out;
            }
            @keyframes fadeIn {
                from { opacity: 0; transform: translateY(10px); }
                to { opacity: 1; transform: translateY(0); }
            }
        }
    </style>
</head>
<body class="bg-gray-50 min-h-screen">
    <div class="container mx-auto px-4 py-8 max-w-5xl">
        <!-- 标题 -->
        <header class="text-center mb-12">
            <h1 class="text-[clamp(2rem,5vw,3rem)] font-bold text-gray-800 mb-3">
                <i class="fa fa-comments text-primary"></i> 文本情感分析系统
            </h1>
            <p class="text-gray-600 max-w-2xl mx-auto">
                基于人工智能的文本情感分析工具，帮助您快速理解文本中的情感倾向（积极、消极或中性）
            </p>
        </header>

        <div class="grid grid-cols-1 lg:grid-cols-3 gap-8">
            <!-- 左侧输入区域 -->
            <div class="lg:col-span-2 space-y-6">
                <div class="bg-white rounded-xl p-6 card-shadow animate-fade-in">
                    <h2 class="text-xl font-semibold text-gray-800 mb-4">输入文本</h2>
                    <textarea id="text-input" rows="6" 
                        class="w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary/50 focus:border-primary transition-all duration-300"
                        placeholder="请输入要分析的中文文本..."></textarea>
                    <div class="flex justify-end mt-4">
                        <button id="analyze-btn" 
                            class="bg-primary hover:bg-primary/90 text-white px-6 py-2 rounded-lg transition-all duration-300 flex items-center">
                            <i class="fa fa-magic mr-2"></i> 分析情感
                        </button>
                    </div>
                </div>

                <!-- 结果展示 -->
                <div id="result-container" class="bg-white rounded-xl p-6 card-shadow animate-fade-in hidden">
                    <h2 class="text-xl font-semibold text-gray-800 mb-4">分析结果</h2>
                    <div id="result-content" class="space-y-4">
                        <div class="bg-gray-50 p-4 rounded-lg">
                            <p class="font-medium text-gray-700 mb-2">原始文本:</p>
                            <p id="result-text" class="text-gray-800"></p>
                        </div>
                        <div class="space-y-3">
                            <div class="flex justify-between items-center">
                                <span class="font-medium text-gray-700">情感分类:</span>
                                <span id="result-sentiment" class="font-semibold text-lg"></span>
                            </div>
                            <div class="flex justify-between items-center">
                                <span class="font-medium text-gray-700">置信度:</span>
                                <div class="w-3/5 bg-gray-200 rounded-full h-2.5">
                                    <div id="result-confidence-bar" class="h-2.5 rounded-full transition-all duration-700"></div>
                                </div>
                                <span id="result-confidence-text" class="font-medium"></span>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- 右侧历史记录 -->
            <div class="lg:col-span-1 space-y-6">
                <div class="bg-white rounded-xl p-6 card-shadow animate-fade-in">
                    <h2 class="text-xl font-semibold text-gray-800 mb-4 flex justify-between items-center">
                        历史记录
                        <span id="history-count" class="text-sm bg-primary/10 text-primary px-2 py-1 rounded-full">0</span>
                    </h2>
                    <div id="history-list" class="space-y-3 max-h-[500px] overflow-y-auto pr-2">
                        <p class="text-gray-500 italic text-center">暂无分析记录</p>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <footer class="mt-16 py-6 bg-gray-800 text-white">
        <div class="container mx-auto px-4 text-center">
            <p>© 2025 文本情感分析系统 | 基于大模型辅助开发</p>
        </div>
    </footer>

    <script>
        document.addEventListener('DOMContentLoaded', function() {
            const analyzeBtn = document.getElementById('analyze-btn');
            const textInput = document.getElementById('text-input');
            const resultContainer = document.getElementById('result-container');
            const resultText = document.getElementById('result-text');
            const resultSentiment = document.getElementById('result-sentiment');
            const resultConfidenceBar = document.getElementById('result-confidence-bar');
            const resultConfidenceText = document.getElementById('result-confidence-text');
            const historyList = document.getElementById('history-list');
            const historyCount = document.getElementById('history-count');

            // 初始加载历史记录
            loadHistory();

            // 分析按钮点击事件
            analyzeBtn.addEventListener('click', async function() {
                const text = textInput.value.trim();
                if (!text) {
                    alert('请输入要分析的文本');
                    return;
                }

                try {
                    // 显示加载状态
                    analyzeBtn.disabled = true;
                    analyzeBtn.innerHTML = '<i class="fa fa-spinner fa-spin mr-2"></i> 分析中...';

                    // 调用API
                    const response = await fetch('/api/analyze', {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json'
                        },
                        body: JSON.stringify({ text })
                    });

                    if (!response.ok) {
                        throw new Error('API请求失败');
                    }

                    const data = await response.json();
                    displayResult(data);
                    loadHistory();

                    // 清空输入框
                    textInput.value = '';
                } catch (error) {
                    console.error('分析出错:', error);
                    alert('分析失败，请重试');
                } finally {
                    // 恢复按钮状态
                    analyzeBtn.disabled = false;
                    analyzeBtn.innerHTML = '<i class="fa fa-magic mr-2"></i> 分析情感';
                }
            });

            // 显示分析结果
            function displayResult(data) {
                resultContainer.classList.remove('hidden');
                resultText.textContent = data.text;
                
                // 设置情感标签和颜色
                let sentimentClass = '';
                let sentimentIcon = '';
                
                if (data.sentiment === '积极') {
                    sentimentClass = 'text-positive';
                    sentimentIcon = '<i class="fa fa-smile-o mr-2"></i>';
                } else if (data.sentiment === '消极') {
                    sentimentClass = 'text-negative';
                    sentimentIcon = '<i class="fa fa-frown-o mr-2"></i>';
                } else {
                    sentimentClass = 'text-neutral';
                    sentimentIcon = '<i class="fa fa-meh-o mr-2"></i>';
                }
                
                resultSentiment.className = `font-semibold text-lg ${sentimentClass}`;
                resultSentiment.innerHTML = `${sentimentIcon}${data.sentiment}`;
                
                // 设置置信度
                const confidence = Math.round(data.confidence * 100);
                resultConfidenceBar.style.width = `${confidence}%`;
                resultConfidenceBar.className = `h-2.5 rounded-full transition-all duration-700 ${
                    confidence >= 70 ? 'bg-positive' : confidence <= 30 ? 'bg-negative' : 'bg-neutral'
                }`;
                resultConfidenceText.textContent = `${confidence}%`;
                
                // 滚动到结果区域
                resultContainer.scrollIntoView({ behavior: 'smooth', block: 'start' });
            }

            // 加载历史记录
            async function loadHistory() {
                try {
                    const response = await fetch('/api/history');
                    if (!response.ok) {
                        throw new Error('获取历史记录失败');
                    }
                    
                    const history = await response.json();
                    renderHistory(history);
                } catch (error) {
                    console.error('加载历史记录出错:', error);
                }
            }

            // 渲染历史记录
            function renderHistory(history) {
                historyList.innerHTML = '';
                historyCount.textContent = history.length;
                
                if (history.length === 0) {
                    historyList.innerHTML = '<p class="text-gray-500 italic text-center">暂无分析记录</p>';
                    return;
                }
                
                history.forEach(record => {
                    const item = document.createElement('div');
                    item.className = 'p-3 border border-gray-100 rounded-lg hover:bg-gray-50 transition-colors duration-200';
                    
                    let sentimentClass = '';
                    let sentimentIcon = '';
                    
                    if (record.sentiment === '积极') {
                        sentimentClass = 'text-positive';
                        sentimentIcon = '<i class="fa fa-smile-o"></i>';
                    } else if (record.sentiment === '消极') {
                        sentimentClass = 'text-negative';
                        sentimentIcon = '<i class="fa fa-frown-o"></i>';
                    } else {
                        sentimentClass = 'text-neutral';
                        sentimentIcon = '<i class="fa fa-meh-o"></i>';
                    }
                    
                    // 截取文本前30个字符
                    const shortText = record.text.length > 30 
                        ? record.text.substring(0, 30) + '...' 
                        : record.text;
                    
                    item.innerHTML = `
                        <div class="flex justify-between items-start">
                            <div class="flex-1 min-w-0">
                                <p class="text-sm font-medium text-gray-800 truncate">${shortText}</p>
                                <p class="text-xs text-gray-500 mt-1">${record.create_time}</p>
                            </div>
                            <span class="ml-2 ${sentimentClass}">${sentimentIcon}</span>
                        </div>
                    `;
                    
                    // 点击查看详情
                    item.addEventListener('click', () => {
                        displayResult({
                            text: record.text,
                            sentiment: record.sentiment,
                            confidence: record.confidence
                        });
                    });
                    
                    historyList.appendChild(item);
                });
            }
        });
    </script>
</body>
</html>    